<?php date_default_timezone_set("PRC");
function  getOpenBodySig($body){
    $appid = '银商提供';
	$appkey = '银商提供';
	$timestamp = date("YmdHis",time());
	$nonce = md5(uniqid(microtime(true),true));
	$str = bin2hex(hash('sha256', $body, true));

	$signature = base64_encode(hash_hmac('sha256', "$appid$timestamp$nonce$str", $appkey, true));

    $authorization = "OPEN-BODY-SIG AppId=\"$appid\", Timestamp=\"$timestamp\", Nonce=\"$nonce\", Signature=\"$signature\"";
    echo $authorization."<br/>";
    return $authorization;

}
function curlpost($url,$body){

    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($body),
        'Authorization: '.getOpenBodySig($body)
        ));
    $output = curl_exec($ch);//运行curl
    echo "响应报文：".$output."<br/>";
    curl_close($ch);
    return $output;

}


function getBillNo($msgSrcId){
    $billNo=$msgSrcId.date("YmdHis",time()).str_pad(mt_rand(0, 999999), 6, "0", STR_PAD_BOTH);
    return $billNo;
}


function makeSign($md5Key, $params) {
    $str = buildSignStr($params) . $md5Key;
    //file_put_contents('log.txt', "待验签字符串:".$str."\r\n", FILE_APPEND);
    console("待验签字符串:".$str."\r\n");
    if($params['signType']=='SHA256'){
        return strtoupper(hash('sha256',$str));
    }
    return strtoupper(hash('md5',$str));
}


// 获取加密的参数字符串
function buildSignStr($params) {
    $keys = [];
    foreach($params as $key => $value) {
        if ($key == 'sign' || is_null($value)) {
            continue;
        }
        array_push($keys, $key);
    }
    $str = '';
    sort($keys);
    $len = count($keys);
    for($i = 0; $i < $len; $i++) {
        $v = $params[$keys[$i]];
        if (is_array($v)) {
            $v = json_encode($v);
        }
        $str .= $keys[$i] . '=' . $v . (($i === $len -1) ? '' : "&");
    }
    return $str;
}

function console($data){
    $stdout = fopen('php://stdout', 'w');
    fwrite($stdout,$data."\n");
    fclose($stdout);
}


